# 行业轮动与个股轮动研究

import pandas as pd
import tushare as ts
import datetime as dt
import matplotlib.pyplot as plt
from matplotlib import style
from mpl_finance import candlestick_ohlc
import matplotlib.dates as mdates
ts.set_token('883c1e2da92c0f68194fe2c4b4aa0e4da880b41ef62ff556f2da00e7')
pro = ts.pro_api()

excelFile = r'C:\Users\ZQ_HHX\PycharmProjects\untitled3\index.xlsx'
df = pd.DataFrame(pd.read_excel(excelFile))
df.columns = ['ts_code','name','date','open','high','low','close','vol','amount','pct_chg']


df4 = pro.index_daily(ts_code='000001.SH', start_date='20050101', end_date='20190516')
df4.index = pd.DatetimeIndex(df4['trade_date'])

style.use('ggplot')

df_ohlc = df4['close'].resample('5D').ohlc()
df_ohlc.reset_index(inplace=True)
df_ohlc['trade_date'] = df_ohlc['trade_date'].map(mdates.date2num)

codeList = [x for x in df['ts_code']]
codeList = list(set(codeList))
df = df.set_index([df['ts_code'], df['date']], drop=True)
for code in codeList:

    df_s_holders = df.loc[code]
    df_s_holders.index = pd.DatetimeIndex(df_s_holders['date'])
    name = df_s_holders['name'].values

    df_volume = df4['amount'].resample('5D').sum()

    fig = plt.figure(figsize=(16, 8))
    ax1 = plt.subplot2grid((6, 1), (0, 0), rowspan=5, colspan=1)
    ax2 = plt.subplot2grid((6, 1), (5, 0), rowspan=1, colspan=1, sharex=ax1)
    ax3 = ax1.twinx()
    ax1.xaxis_date()

    candlestick_ohlc(ax1, df_ohlc.values, width=1.5, colorup='g')
    ax3.plot(df_s_holders.index, df_s_holders['close'].values, color='purple')
    ax2.fill_between(df_volume.index.map(mdates.date2num), df_volume.values, 0)

    plt.savefig('./' + str(code) +name[-1]+ '.jpg', dpi=300)
    plt.clf()

